using muduoDotNet;
using muduoDotNet.Messages;
using Google.Protobuf;
using muduoDotNet.Common;

namespace muduoDotNet.Examples
{
    /// <summary>
    /// 增强版服务器示例，演示如何使用连接池、恢复管理、性能监控和配置管理
    /// </summary>
    public class EnhancedServerExample
    {
        private readonly EventLoop _loop;
        private readonly TcpServer _server;
        private int _connectionCount = 0;

        public EnhancedServerExample(int port = 8080)
        {
            // 初始化配置
            var config = Configuration.GetInstance();
            config.SetValue("performance.connection.pool.enabled", true);
            config.SetValue("performance.connection.pool.min", 5);
            config.SetValue("performance.connection.pool.max", 20);
            config.SetValue("network.recovery.enabled", true);
            config.SetValue("network.reconnect.attempts", 3);
            config.SetValue("network.reconnect.interval.ms", 2000);
            config.SetValue("monitoring.enabled", true);
            
            _loop = new EventLoop();
            _server = new TcpServer(_loop, "127.0.0.1", port);
            
            // 设置服务器回调
            _server.ConnectionCallback = OnConnection;
            _server.MessageCallback = OnMessage;
            _server.WriteCompleteCallback = OnWriteComplete;
            
            Logger.Info($"Enhanced Server will listen on port {port}");
        }

        /// <summary>
        /// 连接建立/断开回调
        /// </summary>
        private void OnConnection(TcpConnection connection)
        {
            if (connection.State == TcpConnectionState.Connected)
            {
                _connectionCount++;
                Logger.Info($"New connection established: {connection.Name} from {connection.RemoteEndPoint}");
                Logger.Info($"Total connections: {_connectionCount}");
                
                // 为新连接设置protobuf消息回调
                connection.SetProtocolMessageCallback<EchoRequest>(OnEchoRequest);
                connection.SetProtocolMessageCallback<Heartbeat>(OnHeartbeat);
                connection.SetProtocolMessageCallback<StatusMessage>(OnStatusMessage);
                
                // 发送连接确认消息
                var welcomeStatus = new StatusMessage
                {
                    Type = StatusMessage.Types.StatusType.Info,
                    Message = "Welcome to Enhanced Server!",
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                welcomeStatus.Metadata.Add("server_version", "1.0.0");
                welcomeStatus.Metadata.Add("protocol", "protobuf");
                
                connection.SendProtobufMessage(welcomeStatus);
            }
            else
            {
                _connectionCount--;
                Logger.Info($"Connection disconnected: {connection.Name}");
                Logger.Info($"Total connections: {_connectionCount}");
            }
        }

        /// <summary>
        /// 原始消息回调（用于处理非protobuf数据）
        /// </summary>
        private void OnMessage(TcpConnection connection, Buffer buffer)
        {
            // 如果有未被协议解析器处理的原始数据，在这里处理
            if (buffer.ReadableBytes > 0)
            {
                var rawData = buffer.RetrieveAllAsString();
                Logger.Warning($"Received unrecognized raw data from {connection.Name}: {rawData}");
                
                // 发送错误状态消息
                var errorStatus = new StatusMessage
                {
                    Type = StatusMessage.Types.StatusType.Error,
                    Message = "Unrecognized message format. Please use protobuf protocol.",
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                connection.SendProtobufMessage(errorStatus);
            }
        }

        /// <summary>
        /// 处理Echo请求
        /// </summary>
        private void OnEchoRequest(TcpConnection connection, EchoRequest request)
        {
            Logger.Info($"Received EchoRequest from {connection.Name}: '{request.Message}' (client: {request.ClientId})");
            
            // 创建Echo响应
            var response = new EchoResponse
            {
                Message = $"Echo: {request.Message}",
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                ServerId = "EnhancedServer",
                StatusCode = 200
            };
            
            // 发送响应
            connection.SendProtobufMessage(response);
            Logger.Debug($"Sent EchoResponse to {connection.Name}: '{response.Message}'");
        }

        /// <summary>
        /// 处理心跳消息
        /// </summary>
        private void OnHeartbeat(TcpConnection connection, Heartbeat heartbeat)
        {
            Logger.Debug($"Received Heartbeat from {connection.Name} (node: {heartbeat.NodeId})");
            
            // 回复心跳
            var heartbeatResponse = new Heartbeat
            {
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                NodeId = "EnhancedServer"
            };
            
            connection.SendProtobufMessage(heartbeatResponse);
        }

        /// <summary>
        /// 处理状态消息
        /// </summary>
        private void OnStatusMessage(TcpConnection connection, StatusMessage status)
        {
            var typeStr = status.Type.ToString();
            Logger.Info($"Received StatusMessage from {connection.Name}: [{typeStr}] {status.Message}");
            
            if (status.Metadata.Count > 0)
            {
                foreach (var kv in status.Metadata)
                {
                    Logger.Debug($"  Metadata: {kv.Key} = {kv.Value}");
                }
            }
        }

        /// <summary>
        /// 写完成回调
        /// </summary>
        private void OnWriteComplete(TcpConnection connection)
        {
            Logger.Debug($"Write completed for connection: {connection.Name}");
        }

        /// <summary>
        /// 启动服务器
        /// </summary>
        public void Start()
        {
            Logger.Info("Starting Enhanced Server...");
            _server.Start();
            Logger.Info("Enhanced Server started successfully!");
        }

        /// <summary>
        /// 停止服务器
        /// </summary>
        public void Stop()
        {
            Logger.Info("Stopping Enhanced Server...");
            _server.Stop();
            _loop.Stop();
            Logger.Info("Enhanced Server stopped.");
        }

        /// <summary>
        /// 运行服务器
        /// </summary>
        public void Run()
        {
            Start();
            
            Logger.Info("Press 'q' to quit the server, 's' to show stats, 'r' to show performance report...");
            
            // 在后台线程运行事件循环
            var loopTask = Task.Run(() =>
            {
                try
                {
                    _loop.Start();
                }
                catch (Exception ex)
                {
                    Logger.Error("Event loop error", ex);
                }
            });

            // 主线程处理用户输入
            while (true)
            {
                var key = Console.ReadKey(true);
                if (key.KeyChar == 'q' || key.KeyChar == 'Q')
                {
                    break;
                }
                else if (key.KeyChar == 's' || key.KeyChar == 'S')
                {
                    // 显示服务器状态
                    Logger.Info($"Server Status: {_connectionCount} active connections");
                    
                    // 显示连接池状态
                    if (_server.ConnectionPool != null)
                    {
                        Logger.Info($"Connection Pool - Available: {_server.ConnectionPool.AvailableConnectionCount}, Active: {_server.ConnectionPool.ActiveConnectionCount}");
                    }
                }
                else if (key.KeyChar == 'r' || key.KeyChar == 'R')
                {
                    // 显示性能报告
                    Logger.Info(PerformanceCounters.GetPerformanceReport());
                }
            }

            Stop();
            loopTask.Wait(5000); // 等待事件循环结束
        }

        /// <summary>
        /// 示例运行方法
        /// </summary>
        public static void RunExample()
        {
            try
            {
                var server = new EnhancedServerExample(8080);
                server.Run();
            }
            catch (Exception ex)
            {
                Logger.Error("Server error", ex);
            }
        }
    }
}